from flask import render_template, g, redirect, request, jsonify, session, current_app, abort, url_for

from info import constants, db
from info.models import Category, News, User
from info.response_code import RET
from info.utils.common import user_login_data
from info.utils.image_storge import storage
from . import profile_blu


@profile_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def user_base_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_base_info.html', data={'user_info': user.to_dict()})

    # 获取参数
    params_dict = request.json
    nick_name = params_dict.get('nick_name')
    signature = params_dict.get('signature')
    gender = params_dict.get('gender')

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if gender not in ('MAN', 'WOMAN'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    session['nick_name'] = nick_name

    return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def user_pic_info():
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={'user_info': g.user.to_dict()})

    try:
        avatar_file = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        avatar_url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='第三方错误')

    g.user.avatar_url = avatar_url
    return jsonify(errno=RET.OK, errmsg='OK', data={'avatar_url': constants.QINIU_DOMIN_PREFIX + avatar_url})


@profile_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def user_pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html', data={'user_info': user.to_dict()})

    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='原密码错误')

    user.password = new_password
    return jsonify(errno=RET.OK, errmsg='OK')


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    user = g.user
    page = request.args.get('page', 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    collection_list = []
    current_page = 1
    total_pages = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        collection_list = paginate.items
        current_page = paginate.page
        total_pages = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    collection_dict = []
    for collection_news in collection_list:
        collection_dict.append(collection_news.to_basic_dict())

    data = {
        "collection_dict": collection_dict,
        "current_page": current_page,
        "total_pages": total_pages
    }
    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def user_news_release():
    user = g.user
    if request.method == 'GET':
        categories = []
        try:
            # 获取所有分类
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict = []
        for category in categories:
            category_dict.append(category.to_dict())

        category_dict.pop(0)
        return render_template('news/user_news_release.html', data={'category_dict': category_dict})

    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    source = '个人发布'

    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 将标题图片上传到七牛
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 初始化news模型,设置数据
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.source = source
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.content = content
    news.user_id = user.id

    # 设置为待审核状态
    news.status = 1
    db.session.add(news)
    return jsonify(errno=RET.OK, errmsg='发布成功,等待审核!')


@profile_blu.route('/news_list')
@user_login_data
def user_news_list():
    user = g.user
    page = request.args.get('page', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_pages = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.HOME_PAGE_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_pages = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict = []
    for news in news_list:
        news_dict.append(news.to_review_dict())

    data = {
        'news_dict': news_dict,
        'current_page': current_page,
        'total_pages': total_pages
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/info')
@user_login_data
def user_center():
    if not g.user:
        return redirect('/passport/login')
    data = {
        'user_info': g.user.to_dict()
    }
    return render_template('news/user.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user
    page = request.args.get('page', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user_followed = []
    current_page = 1
    total_pages = 1
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        user_followed = paginate.items
        current_page = paginate.page
        total_pages = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_followed_list = []
    for follow_user in user_followed:
        user_followed_list.append(follow_user.to_dict())

    data = {
        'user_followed': user_followed_list,
        'current_page': current_page,
        'total_pages': total_pages
    }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """查询其他用户信息"""

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    user_id = request.args.get('id')

    if not user_id:
        abort(404)

    other_user = None
    try:
        other_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other_user:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if user:
        if user in other_user.followers:
            is_followed = True

    data = {
        "user_info": user.to_dict(),
        "other_info": other_user.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)


@profile_blu.route('/other_news_list')
def other_news_list():
    """其他用户发布的新闻列表"""
    # 获取页数
    page = request.args.get("page", 1)
    user_id = request.args.get("user_id")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([page, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
